$(function() {
	preload.setCache(g);
	preload.push('bags', {
		url: g.serviceUrl,
		data: {
			op: 'getBags',
			keyWord: '',
			pageSize: 100000,
			pageIndex: 0
		}
	});
	preload.push('tags', {
		url: g.serviceUrl,
		data: {
			op: 'getTagsForAdmin',
			status: 1,
			pageSize: 100000,
			pageIndex: 0
		}
	});
	preload.run(start);
});

function start() {

	init();
}

function init() {

	create();

	attach();

	first();

	function create() {



		// 是否订阅
		createStatusSel();

		// 表格
		createDg();

		// pager
		createPager();

		// 表单
		createFrm();



		function createStatusSel() {
			var statusSel = $('#statusSel');
			var data = [{
				value: 1,
				text: '订阅'
			}, {
				value: 0,
				text: '空置'
			}];
			statusSel.combobox('loadData', data);
			statusSel.combobox('select', 1);
		}


		function createDg() {
			var dg = $('#dg');
			dg.datagrid({
				striped: true,
				singleSelect: true,
				fitColumns: true,
				columns: [
					[{
						field: 'id',
						title: '编号',
						width: 50
					}, {
						field: 'name',
						title: '视频',
						width: 120,
						formatter: function(value, row, index) {
							var color = row.status ? 'steelblue' : 'gray';
							return ['<span style="color:', color, ';">', value, '</span>'].join('');
						}
					}, {
						field: 'tagId',
						title: '标签名列表',
						width: 200,
						formatter: function(value, row, index) {
							var arr = [];
							$.each((value + '').split(','), function(i, n) {
								var item = JSLINQ(g.tags.data[0]).First(function(c) {
									if(c.id == n) {
										return c;
									}
								});
								if(item) {
									arr.push(item.name);
								}

							});
							return arr.join(',');

						}
					},

					{
						field: 'owner',
						title: '创建者',
						width: 120
					}]
				]
			});

		}

		function createPager() {
			var pager = $('#pager');
			pager.pagination({
				pageNumber: 1,
				pageSize: 12

			});
		}

		function createFrm() {

			// tag
			createTagSel();


			// status
			createStatusSel();

			function createTagSel() {
				var tagSel = $('#frmTagSel');
				var tree = tagSel.combotree('tree');
				tree.tree({
					onlyLeafCheck: true
				});
				var data = formatter(g.bags.data[0], g.tags.data[0]);



				tagSel.combotree('loadData', data);

				function formatter(bags, tags) {
					var rst = [];
					$.each(bags, function(i, n) {
						var bitem = {
							id: n.id,
							text: n.name,
							children: []
						};
						$.each(tags, function(ii, nn) {
							if(n.id == nn.bagId) {
								var titem = {
									id: nn.id,
									text: nn.name
								};
								bitem.children.push(titem);
							}
						});
						rst.push(bitem);
					});
					return rst;

				}
			}

			function createStatusSel() {
				var statusSel = $('#frmStatusSel');
				var data = [{
					value: 1,
					text: '订阅'
				}, {
					value: 0,
					text: '空置'
				}];
				statusSel.combobox('loadData', data);
				statusSel.combobox('select', 1);
			}
		}
	}



	function attach() {
		// 按钮
		attachSearchBtn();



		// 表格
		attachDg();
		// pager
		attachPager();
		// 表单
		attachFrm();

		function attachDg() {
			var dg = $('#dg');
			dg.datagrid({
				'onClickRow': function(rowIndex, rowData) {
					console.log('onClickRow');
					frm.setData(rowData.id);
					$('#opDist').panel('expand');
					$('#frmToolbar a[ptag="edit"]').trigger('click');
				}
			});
		}


		function attachSearchBtn() {
			var searchBtn = $('#searchBtn');
			searchBtn.bind('click', function(e) {
				proxy.getData();
			});
		}

		function attachPager() {
			var pager = $('#pager');
			pager.pagination({
				onSelectPage: function(pageNumber, pageSize) {
					console.log(pageNumber, pageSize);
					proxy.getData();
				},
				onRefresh: function() {
					proxy.getData();
				}
			});
		}

		function attachFrm() {
			// intervalSel will be 'enable' when STATUS equal 1
			$('#frmStatusSel').combobox({
				'onChange': function(newValue, oldValue) {
					$('#frmIntervalSel').combobox(newValue == 1 && frm._mode == 'edit' ? 'enable' : 'disable');
				}
			});
			$('#frmToolbar a').click(function(e) {
				// alert($(this).text());
				var ptag = $(this).attr('ptag');
				// 一切都显示 在具体的分类中再进行隐藏
				var trs = $('#opDist tr');
				trs.show();
				var FinderIdNode = $('#frmFinderIdTb');
				var FinderNameNode = $('#frmFinderNameTb');
				var tagNode = $('#frmTagSel');
				var statusNode = $('#frmStatusSel');
				var intervalNode = $('#frmIntervalSel');
				var dic = {
					"add": function() {
						trs.filter('[ptag="id"],[ptag="status"],[ptag="interval"]').hide();
						FinderNameNode.prop('disabled', false);
						intervalNode.combobox('disable');
						frm._mode = 'add';
					},
					"edit": function() {

						FinderIdNode.prop('disabled', true);
						FinderNameNode.prop('disabled', false);
						tagNode.combotree('enable');
						statusNode.combobox('enable');
						intervalNode.combobox('disable');
						frm._mode = 'edit';

						// trigger statusSel
						statusNode.combobox('getValue');
					},
					"remove": function() {
						FinderIdNode.prop('disabled', true);
						FinderNameNode.prop('disabled', true);
						tagNode.combotree('disable');
						statusNode.combobox('disable');
						intervalNode.combobox('disable');
						frm._mode = 'remove';
					}
				};
				dic[ptag] && dic[ptag]();
			});

			// ok btn
			$('#frmToolbarSec a').click(function(e) {
				var ptag = $(this).attr('ptag');
				var dic = {
					"ok": function() {
						var mode = frm._mode;
						var dic = {
							'add': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'insertFinder'
								}, data);

								var callback = function(data) {
										if(data.flag) {
											proxy.getData();
										} else {
											$.messager.alert('Remote Err', data.msg);
										}
									};
								$.post(url, params, callback);
							},
							'edit': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'editFinder'
								}, data);
								var callback = function(data) {
										if(data.flag) {


											// about subscribe
											var fdata = frm.getData();
											var finderId = fdata.finderId;
											var odata = JSLINQ(g.dgData.data[0]).First(function(c) {
												return c.id == finderId;
											});

											var op;
											if(odata.status != fdata.status) {
												op = fdata.status == 1 ? 'insertSubscribe' : 'deleteSubscribe';
											} else if(fdata.status == 1 && fdata.interval != odata.interval) {
												op = 'editSubscribe';
											}
											if(op) {
												var url = g.serviceUrl;
												var params = $.extend({
													op: op
												}, fdata);
												var callback = function(data) {
														proxy.getData();
													};
												$.post(url, params, callback);

											}
											else{
												proxy.getData();
											}
										} else {
											$.messager.alert('Remote Err', data.msg);
										};

									};
								$.post(url, params, callback);
							},
							'remove': function(data) {
								var url = g.serviceUrl;
								var params = $.extend({
									op: 'deleteFinder'
								}, data);
								var callback = function(data) {
										if(data.flag) {
											proxy.getData();
										} else {
											$.messager.alert('Remote Err', data.msg);
										}
									};
								$.post(url, params, callback);
							}
						};
						if(dic[mode]) {
							var data = frm.getData();
							// simple formatter 
							data.videoId = data.id;
							if(frm.check(data)) {
								dic[mode](data);
							} else {
								$.messager.alert('Warn', '参数检测错误!!');
							}
						}
					}
				};
				dic[ptag] && dic[ptag]();
			});
		}
	}

	function first() {
		var searchBtn = $('#searchBtn');
		searchBtn.trigger('click');
	}
}

function getParams() {

	// tagIds
	var userTb = $('#userTb');
	var user = userTb.val();

	// status
	var statusSel = $('#statusSel');
	var status = statusSel.combobox('getValue');

	// pager
	var pager = $('#pager');
	var pagerOpts = pager.pagination('options');
	var pageIndex = pagerOpts.pageNumber - 1;
	var pageSize = pagerOpts.pageSize;

	var rst = {
		op: 'searchFinderForAdmin',
		user: user,
		status: status,
		pageSize: pageSize,
		pageIndex: pageIndex
	};
	return rst;
}


function getData(params, next) {

	var url = g.serviceUrl;
	var data = params;


	var callback = function(d) {

			if(!d.flag) {
				alert(d.msg);
			} else {
				g.dgData = d;
				next && next(d.data);
			}



		};
	$.post(url, data, callback);



}

function disp(data) {
	var dg = $('#dg');


	var total = data[1];
	var rows = format(data[0]);
	dg.datagrid('loadData', {
		total: total,
		rows: rows
	});

	// 格式化数据

	function format(data) {
		var rst = [];
		var dic = {};
		$.each(data, function(i, n) {
			var item;
			if(!dic[n.id]) {
				dic[n.id] = true;
				rst.push($.extend({}, n));
			} else {
				var item = JSLINQ(rst).First(function(c) {
					return c.id == n.id;
				});
				item.tagId = [item.tagId, n.tagId].join(',');
			}
		});

		return rst;

		function parseDt(dt) {
			var num = (dt.match(/\d+/)[0]) - 0;
			var time = new Date(num);
			return time.toString('yyyy年MM月dd日');
		}
	}
}

function setPager(data) {
	var pager = $('#pager');
	var total = data[1];
	var opts = pager.pagination('options');
	var pageIndex = Math.min(opts.pageNumber, total) - 1;
	pager.pagination({
		total: total,
		pageNumber: pageIndex + 1
	});
}


// 通过id在form中展示数据
var frm = {
	setData: function(id) {
		var data = null;
		if(typeof(id) == "number") {
			var arr = JSLINQ(g.dgData.data[0]).Where(function(c) {
				return c.id == id;
			}).ToArray();

			$.each(arr, function(i, n) {
				if(!data) {
					data = $.extend({}, n);
					data.tagId += '';
				} else {
					data.tagId = [data.tagId, n.tagId].join(',');
				}
			});
		}
		if(data) {

			$('#frmFinderIdTb').val(data.id);
			$('#frmFinderNameTb').val(data.name);
			$('#frmTagSel').combotree('setValues', data.tagId.split(','));
			$('#frmStatusSel').combobox('select', data.status);
			$('#frmIntervalSel').combobox('select', data.interval);
		}
	},
	getData: function() {
		var rst = {};
		rst.finderId = $('#frmFinderIdTb').val();
		rst.name = $('#frmFinderNameTb').val();
		rst.tagIds = $('#frmTagSel').combotree('getValues').join(',');
		rst.status = $('#frmStatusSel').combobox('getValue');
		rst.interval = $('#frmIntervalSel').combobox('getValue');
		rst.mode = this._mode;
		return rst;
	},
	check: function() {
		var rst = false;
		var data = this.getData();
		var dic = {
			'add': function(data) {
				return data.name != "" && data.url != "";
			},
			'edit': function(data) {
				return data.id != "" && data.id != -1 && data.name != "" && data.url != "";
			},
			'remove': function(data) {
				return data.id != "" && data.id != -1;
			}
		};
		if(this._mode && dic[this._mode]) {
			rst = dic[this._mode](data);
		}
		return rst;
	},
	_mode: null
};



var g = {
	//dgData
	serviceUrl: '../../service/tagerOp.ashx'
};

// 代理者
var proxy = {
	getData: function() {
		var params = getParams();
		getData(params, function(data) {
			disp(data);
			setPager(data);
		});
	}

};

var formatter = {
	bag: function(data) {
		var rst = [{
			value: -1,
			text: '全部'
		}];
		$.each(data[0], function(i, n) {
			rst.push({
				value: n.id,
				text: n.name
			});
		})
		rst = rst.sort(function(a, b) {
			return a.id - b.id;
		});
		return rst;
	}
};